package com.rech.websocket;

import android.os.Message;
import android.util.Log;

import com.rech.utils.CommandUtil;
import com.rech.utils.LogUtil;
import com.rech.utils.OtherUtil;
import com.rech.xbexpress3.FullscreenActivity;
import com.rech.xbexpress3.QueueService;
import com.rech.xbexpress3.RedisLogic;

import org.greenrobot.eventbus.EventBus;
import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;

import java.net.URI;

import static android.content.ContentValues.TAG;

public class WebSocketClient extends org.java_websocket.client.WebSocketClient {
    public WebSocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        //开启连接
        Log.d("WebSocketClient","onOpen"+"成功连接到："+getRemoteSocketAddress());
        //EventBus.getDefault().post(new MessageEvent(2,"onOpen："+getRemoteSocketAddress()));
        LogUtil.getInstance().info(OtherUtil.getCurrentTime()+" Websocket:"+"onOpen："+getRemoteSocketAddress());
        FullscreenActivity.isClient=true;

    }
    @Override
    public void onMessage(String message) {
        //接受消息
        Log.d("WebSocketClient","onMessage"+message);
        //EventBus.getDefault().post(new MessageEvent(1,getRemoteSocketAddress()+"："+message));
        LogUtil.getInstance().info(OtherUtil.getCurrentTime()+" Websocket:"+"onMessage："+message);
            if(message.length() == 0){
                return ;
            }

            try{
                JSONObject obj = new JSONObject(message);
                {
                    int IO = obj.getJSONObject("data").getInt("IO");
                    int _485 = obj.getJSONObject("data").getInt("485");
                    obj.put("source","redis");
                    obj.getJSONObject("data").put("status","1");//1 1a发送 2 1a发送确认 3 3a成功 4 3a成功确认 5 4a失败 6 4a失败确认 7 1c信息 8 1c信息确认
                    String cmd = CommandUtil.toGetCommand(IO,_485);
                    Log.d(TAG, "Command:"+cmd+"\n");
                    LogUtil.getInstance().info(OtherUtil.getCurrentTime()+" REDIS:"+obj.toString());
                    QueueService.send(cmd,obj,IO);

                    Message msg1 = new Message();
                    msg1.what = 8888;
                    msg1.obj = cmd;
                    EventBus.getDefault().post(msg1);
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }

    }
    @Override
    public void onClose(int code, String reason, boolean remote) {
        //断开连接
        Log.d("WebSocketClient","onClose");
        //EventBus.getDefault().post(new MessageEvent(2,"onClose："+reason));
        LogUtil.getInstance().info(OtherUtil.getCurrentTime()+" Websocket:"+"onClose："+reason);

    }
    @Override
    public void onError(Exception ex) {
        //发生错误
        Log.d("WebSocketClient","onError");
        //EventBus.getDefault().post(new MessageEvent(2,"onError："+ex.toString()));
        LogUtil.getInstance().info(OtherUtil.getCurrentTime()+" Websocket:"+"onError："+ex.toString());

    }
    private static WebSocketClient webSocketClient;
    //发起连接
    public static boolean connect(String ip) {
        if (webSocketClient != null) {
            Release();
        }
        if (webSocketClient == null ) {
            URI uri = URI.create("ws://"+ip+":9505");
            webSocketClient = new WebSocketClient(uri);
        }
        try {
            webSocketClient.connectBlocking();
            return true;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }
    public static void Release() {
        Close();
        webSocketClient = null;
    }
    public static void Close() {
        if (webSocketClient == null) return;
        if (!webSocketClient.isOpen()) return;
        try {
            webSocketClient.closeBlocking();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //发送消息
    public static void Send(String string) {
        if (webSocketClient == null) return;
        if (!webSocketClient.isOpen())
            Reconnect();
        try {
            webSocketClient.send(string);
        } catch (WebsocketNotConnectedException e) {
            e.printStackTrace();
        }
    }
    public static boolean Reconnect() {
        if (webSocketClient == null) return false;
        if (webSocketClient.isOpen()) return true;
        try {
            webSocketClient.reconnectBlocking();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
